// ------------------------------------------------------------------------------------------
// Licensed by Interprise Solutions.
// http://www.InterpriseSolutions.com
// For details on this license please visit  the product homepage at the URL above.
// THE ABOVE NOTICE MUST REMAIN INTACT.
// ------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using InterpriseSuiteEcommerceCommon.ErrorHandlers.Formatters;
using InterpriseSuiteEcommerceCommon.ErrorHandlers.Publishers;
using System.Web;
using InterpriseSuiteEcommerceCommon.Tool;

namespace InterpriseSuiteEcommerceCommon.ErrorHandlers
{
    public static class ExceptionHandler
    {
        public static void Handle(Exception ex)
        {
            // check if we're just checking a 404 error message
            // if such, we just redirect the user to our custom topic page
            if (ex is HttpException)
            {
                HttpException pageNotFoundException = ex as HttpException;
                if (pageNotFoundException.GetHttpCode() == 404)
                {
                    HttpContext.Current.ClearError();
                    HttpContext.Current.Response.Redirect("~/t-error404.aspx");
                }
            }

            string configuredPublishers = AppLogic.AppConfig("ErrorNotification");

            if(CommonLogic.IsStringNullOrEmpty(configuredPublishers)) return;

            bool publishInFile      = CommonLogic.StringInCommaDelimitedStringList("file", configuredPublishers);
            bool publishInEmail     = CommonLogic.StringInCommaDelimitedStringList("email", configuredPublishers);
            bool publishInEventLog  = CommonLogic.StringInCommaDelimitedStringList("eventLog", configuredPublishers);

            if ((publishInFile || publishInEmail || publishInEventLog) == false) return;
            
            // generate a new error code for reference
            string errorCode = Guid.NewGuid().ToString("N").Substring(0, 7).ToUpper();

            IErrorFormatter formatter = new TextErrorFormatter();
            formatter.Prepare(errorCode, ex);

            List<IExceptionPublisher> publishers = new List<IExceptionPublisher>();            

            if (publishInFile)
            {
                publishers.Add(new FileBasedExceptionPublisher());
            }
            if (publishInEmail)
            {
                publishers.Add(new EmailExceptionPublisher());
            }
            if (publishInEventLog)
            {
                publishers.Add(new EventLogExceptionPublisher());
            }

            // if an error occurs be silent about it
            // since these are the ones supposed to send the notification!
            foreach (IExceptionPublisher publisher in publishers)
            {
                try
                {
                    publisher.Publish(errorCode, formatter.Error);
                }
                catch { }
            }
            
            // Now, notify the user on the webpage
            string errorMessage = AppLogic.RunXmlPackage("notification.error.xml.config", 
                                            null,
                                            Customer.Current, 
                                            1, 
                                            string.Empty, 
                                            XmlPackageParam.FromString("errorcode=" + errorCode), 
                                            false, 
                                            false);

            HttpContext ctx = HttpContext.Current;
            ctx.Response.Clear();
            ctx.Response.Write(errorMessage);
            ctx.Response.Flush();
            ctx.Response.End();

            ctx.Server.ClearError();
        }
    }
}
